﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace scanner_tron
{
    internal class tronapi
    {
        public const string apigetblock1 = "https://apilist.tronscan.org/api/block?number=1";
        public const string apilist_trp10 = "https://apilist.tronscan.org/api/asset/transfer?limit=50&start_timestamp=";//1529856000000"
        public const string apilist_trp20 = "https://apilist.tronscan.org/api/token_trc20/transfers?limit=50&start_timestamp=";//1529856000000


        public WebClient wctrp10 = new WebClient();
        public WebClient wctrp20 = new WebClient();

        public long startTimeStamp;
        public List<string> startAddress;
        public async Task Start()
        {
            var str = await wctrp10.DownloadStringTaskAsync(apigetblock1);
            var json = JObject.Parse(str);
            startTimeStamp = (long)(json["data"][0]["timestamp"]); ;
            var time = DateTimeOffset.FromUnixTimeMilliseconds(startTimeStamp);
            Console.WriteLine("Block startTime Stamp=" + time);

            startAddress = new List<string>();
            var arr = json["data"][0]["srConfirmList"] as JArray;
            foreach (var item in arr)
            {
                startAddress.Add(item["address"].ToString());
            }
        }
        public enum Mode
        {
            TRC10,
            TRC20,
        }
        public async Task GetTrcAddr(Mode mode, long time, long endtime, List<string> result, long pageid)
        {
            var endTime = "&end_timestamp=" + endtime;
            var page = "&start=" + pageid;
            var url = ((mode == Mode.TRC10) ? apilist_trp10 : apilist_trp20) + time + endTime + page;
            string str = null;
            if (mode == Mode.TRC10)
            {
                str = await wctrp10.DownloadStringTaskAsync(url);
            }
            else
            {
                str = await wctrp20.DownloadStringTaskAsync(url);
            }
            var json = JObject.Parse(str);
            var d = json["Data"] as JArray;
            if (d == null)
                return;
            foreach (var item in d)
            {
                result.Add(item["transferFromAddress"].ToString());
                result.Add(item["transferToAddress"].ToString());
            }

        }
    }
}
